package com.zzhardy.utils;

import java.io.*;
import java.util.Base64;

import org.apache.commons.io.IOUtils;

public class FileUtils {
    /**
     * 读取文件内容, 如读取json文件
     */
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File file = new File(fileName);
            if (file.exists()) {
                FileReader   fileReader = new FileReader(file);
                Reader       reader     = new InputStreamReader(new FileInputStream(file), "utf-8");
                int          ch         = 0;
                StringBuffer sb         = new StringBuffer();
                while ((ch = reader.read()) != -1) {
                    sb.append((char) ch);
                }
                fileReader.close();
                reader.close();
                jsonStr = sb.toString();
            }
            
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 本地文件（图片、excel等）转换成Base64字符串
     *
     * @param imgPath     
     */
    public static String convertFileToBase64ByIO(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
            byte[]      bytes              = IOUtils.toByteArray(contextClassLoader.getResourceAsStream(imgPath));
            String base64Str = Base64.getEncoder().encodeToString(bytes);
            return "data:image/jpeg;base64," + base64Str;
            
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    
}
